<template>
    <el-tree
            style="max-width: 600px"
            :data="data"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            :default-checked-keys="checked"
            @check-change="handleCheckChange"
    />
    <el-button type="primary" @click="save">保 存</el-button>
</template>
<!--            :default-expanded-keys="[2,3]"
            :default-checked-keys="[5,8]"-->
<script setup lang="ts">

    import { ElTree } from 'element-plus';
    import { ref } from 'vue';

    const { data, update, defaultProps, checked } = defineProps({
        data: {
            type: Object,
            required: true
        },
        checked: {
            type: Array,
            required: false
        },
        update: {
            type: Function,
            required: true
        },
        defaultProps: {
            type: Object,
            required: true
        }
    });

    const checkNode = ref([...checked])

    //复选框被点击的时候触发
    const handleCheckChange = (
        data,
        checked: boolean,
        indeterminate: boolean
    ) => {
        if (data.children) {
            if (checked) {
                //父类被选中
                if (checkNode.value.indexOf(data.id) < 0) {
                    checkNode.value.push(data.id);
                }
                data.children.forEach(item => {
                    if (checkNode.value.indexOf(item.id) < 0) {
                        checkNode.value.push(item.id);
                    }
                })
            } else if (!indeterminate) {
                //节点子树未被选中
                if (checkNode.value.indexOf(data.id) > -1) {
                    checkNode.value.splice(checkNode.value.indexOf(data.id), 1)
                }
                data.children.forEach(item => {
                    if (checkNode.value.indexOf(item.id) > -1) {
                        checkNode.value.splice(checkNode.value.indexOf(item.id), 1)
                    }
                })
            }
        } else {
            //子树中勾选的情况
            const index = checkNode.value.indexOf(data.id);
            if (checked) {
                if (index < 0) {
                    checkNode.value.push(data.id);
                }
            } else {
                if (index > -1) {
                    checkNode.value.splice(index, 1);
                }
            }
        }
    }

    //return data到父节点
    const save = () => {
        update(checkNode.value.join(','));
    }
</script>
